package com.scuola.scuoladocente;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.PreferenceActivity;

public class preferences extends PreferenceActivity {
	
	private Preference prefs;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.prefs);
		prefs = (Preference)findPreference("server_status");
		
		new Thread(getServerStatus).start();
	}


	private Runnable getServerStatus = new Thread() {
		public void run(){
			while(true){
				try{
					SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
					String ws_ip = sharedPreferences.getString("WS_IP", "").toString();
					 
					final String NAMESPACE = "http://scuola.com";
					final String URL = "http://"+ws_ip+":8080/ScuolaWS/services/WebService?wsdl";
					final String SOAP_ACTION = "http://scuola.com/getServerStatus";
					final String METHOD_NAME = "getServerStatus";
					
		        	SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		            envelope.setOutputSoapObject(request);
		            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		            
		            androidHttpTransport.call(SOAP_ACTION, envelope);
		            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
		            
		            if (response.toString().equals("ONLINE")){
		            	runOnUiThread(new Runnable(){
		            		public void run(){
		            			prefs.setSummary("Server: ONLINE");
		            		}
		            	});
		            }
		            
		            Thread.sleep(5000); // Waiting 5000ms before start new server status check
				}catch(Exception e){
					runOnUiThread(new Runnable(){
	            		public void run(){
	            			prefs.setSummary("Server: OFFLINE");
	            		}
	            	});
				}
			}
		}
	};
}

